from Accounting.Fee.FeeBase import Fee
from DataAccess.DBConnFactory import DBConnFactory
from string import Template
from datetime import timedelta


class FetchFeederFee(Fee):
	def __init__(self, ref_date, entity, subtype, is_payment_date, is_redem, curncy):
	
		cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
		sql_tpl = Template('''select feeder_fee_subtype, curncy 
							from fee_conf
							where entity='${ENTITY}'
								and subtype='${TP}' ''')		
		cursor.execute(sql_tpl.substitute(ENTITY=entity.get_entity_id(), 
										TP=subtype))
		r = cursor.fetchall()
		if not r:
			raise RuntimeError(), ("Fee Config Error")

		self.feeder_fee_subtype = r[0][0]
		self.fee_subtype = subtype
		
		Fee.__init__(self, ref_date, r[0][1], is_payment_date, is_redem, entity)
	
	def calculate(self):
	
		cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
		
		sql_tpl = Template('''select sum(amount) from fee,share_account sh
								where fee.entity=sh.child
								and fee.ref_date = sh.ref_date
								and fee.ref_date = TO_DATE('${DATE}','yyyy-mm-dd')
								and fee.subtype = '${FEE_TP}'
								and sh.parent = '${ENTITY}' ''')
		sql_text = sql_tpl.substitute(ENTITY=self.entity.get_entity_id(),
									FEE_TP = self.feeder_fee_subtype,
									DATE=(self.ref_date - timedelta(days=1)).isoformat())
		
		cursor.execute(sql_text)
		r = cursor.fetchall()
		
		if not r:
			raise RuntimeError(), ("Fetch Feeder Fee Error")
		
		self.amt = r[0][0]

		
	def type(self):
		return self.fee_subtype
		
	def category(self):
		return 'PreIAVFee'